import re
import logging
import json
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from django.core import serializers
from django.db.models import Q, F

logger = logging.getLogger('log')
from django.http import JsonResponse
# 只能用相对路径 绝对路径会报错
from ..models import ptResponseContentReport, ptTestRequestTestCase, ptResponseReportResult, ptTestRequest
from ..serverEvCfg import httpResponseSignal


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getReportPlan(request):  # 获取报告内容
    '''
    获取报告计划以及结果
    '''
    try:
        report = ptResponseContentReport.objects.all().order_by('-updata_time')[:5]
        data = json.loads(serializers.serialize("json", report))
        result = ptTestRequestTestCase.objects.all().count()
        Resulreport = ptResponseReportResult.objects.all().order_by('-updata_time')[:7]
        ReportResul = json.loads(serializers.serialize("json", Resulreport))
        for i in range(len(ReportResul)):
            creatTime = ReportResul[i]["fields"]["creat_time"]
            updata_time = ReportResul[i]["fields"]["updata_time"]
            ReportResul[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0]
            ReportResul[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0]
        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["ReportResul"] = ReportResul  # 报告结果
        response["data"] = data  # 报告内容
        response["result"] = result  # 结果数

        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getReportCase(request):  # 获取报告内容
    '''
    获取报告包含的所有设计用例
    '''
    data = json.loads(request.body)
    try:
        report = ptResponseContentReport.objects.filter(plan_id=data["id"]).get()
        # eval(report.store_test_case) 查询对应ID涉及到的所有用例，
        # 并且挑选出符合case_name=data["case_name"] & request_code=data["request_code"]的2个条件的数据
        caseList = ptTestRequestTestCase.objects.filter(case_id__in=eval(report.store_test_case)).filter(
            Q(case_name__icontains=data["case_name"]) & Q(request_code__icontains=data["request_code"]))
        caseListStr = json.loads(serializers.serialize("json", caseList))
        print(caseListStr)
        caseRequestId = []  # 一个用例关联的请求接口列表
        for i in range(len(caseListStr)):
            if caseListStr[i]["fields"]["request_response"] == "":  # 响应为空
                request_response = caseListStr[i]["fields"]["request_response"]
            else:  # 不为空
                request_response = eval(caseListStr[i]["fields"]["request_response"])
            caseListStr[i]["fields"]["request_response"] = json.loads(request_response)
            caseRequestId.append(caseListStr[i]["fields"]["case_request_id"])

        request = ptTestRequest.objects.filter(request_id__in=caseRequestId)
        requestResult = json.loads(serializers.serialize("json", request))

        for i in range(len(caseListStr)):
            for j in range(len(requestResult)):
                if int(caseListStr[i]["fields"]["case_request_id"]) == int(requestResult[j]["pk"]):
                    caseListStr[i]["fields"]["request_address"] = requestResult[j]["fields"]["request_address"]
                    caseListStr[i]["fields"]["request_mode"] = requestResult[j]["fields"]["request_mode"]

        response = httpResponseSignal.httpResponseSignal().getSuccess()
        response["data"] = caseListStr
        return JsonResponse(response)
    except Exception as e:
        logging.error(e)
        response = httpResponseSignal.httpResponseSignal().getErorr()
        return JsonResponse(response)
